import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_demo/http/api.dart';
import 'package:flutter_demo/module/base_infor.dart';
import 'package:flutter_demo/other/application.dart';
import 'package:flutter_demo/widget/buttons.dart';
import 'package:flutter_demo/widget/choose_file.dart';
import 'package:flutter_demo/widget/tiny_widgets.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:universal_html/html.dart' as html;
import 'module/academic_infor.dart';

class ApplyScreen extends StatelessWidget {

  final GlobalKey _formKey = GlobalKey<FormState>();

  final TextEditingController _pNameController = TextEditingController();
  final TextEditingController _pIdController = TextEditingController();
  final TextEditingController _cNameController = TextEditingController();
  final TextEditingController _yearController = TextEditingController();
  final TextEditingController _levelController = TextEditingController();

  late html.File _file;
  late int _dateMill;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Container(
            width: double.infinity,
            height: 60,
            padding: EdgeInsets.symmetric(
              horizontal: 195,
            ),
            decoration: BoxDecoration(
              color: Color(0xff1a56a8),
            ),
            child: Container(
              width: 580,
              height: 59,
              alignment: Alignment.centerLeft,
              child: Image(
                image: NetworkImage('http://my.gxrczc.com/assets/img/logo_zc.png'),
              ),
            ),
          ),
          Expanded(
            child: Container(
              width: double.infinity,
              height: double.infinity,
              alignment: Alignment.center,
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: NetworkImage(
                    'http://my.gxrczc.com/assets/img/bg.png',
                  ),
                  fit: BoxFit.cover,
                ),
              ),
              child: Container(
                width: 805,
                margin: EdgeInsets.symmetric(
                  vertical: 17,
                ),
                decoration: BoxDecoration(
                  color: Colors.white,
                ),
                child: CustomScrollView(
                  slivers: [
                    secction('基本信息'),
                    BaseInforModule(),
                    secction('学历信息'),
                    AcademicInforModule(),
                    bottom(context),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
  
  Widget secction(String title) {
    return SliverToBoxAdapter(
      child: Container(
        height: 54,
        alignment: Alignment.centerLeft,
        padding: EdgeInsets.only(
            left: 30,
            top: 30
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
              width: 3,
              height: 14,
              decoration: BoxDecoration(
                color: Color(0xff6AA2E4),
              ),
            ),
            C(10),
            Text(
              title,
              style: TextStyle(
                color: Color(0xff333333),
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget bottom(BuildContext context) {
    return SliverToBoxAdapter(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          C(30),
          Form(
            key: _formKey,
            child: Wrap(
              spacing: 30,
              runSpacing: 20,
              children: [
                formField('真实姓名', 4, _pNameController),
                formField('身份证号', 19, _pIdController),
                formField('单位名称', 10, _cNameController),
                formField('申报年度', 4, _yearController),
                ChooseDateView(title: '申报日期',
                    callback: (mill) => _dateMill = mill),
                formField('申报级别', 4, _levelController),
              ],
            ),
          ),
          C(30),
          Container(
            alignment: Alignment.center,
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                ChooseFileView(title: '附件', callback: (file) => _file = file),
                C(20),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    C(20),
                    Text(
                      '附件要求',
                      style: TextStyle(
                        fontSize: 18.72,
                        fontWeight: FontWeight.bold,
                        color: Color(0xff303133),
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.symmetric(
                        vertical: 14,
                      ),
                      child: Text(
                        '请上传word/pdf格式的简历',
                        style: TextStyle(
                          fontSize: 14,
                          color: Color(0xffd9524e),
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
          C(30),
          Container(
            padding: EdgeInsets.symmetric(
              horizontal: 120,
            ),
            child: BaseButton(
              radius: 21,
              height: 46,
              withBorder: false,
              withShadow: false,
              buttonColor: Colors.blue,
              onTap: () {
                if ((_formKey.currentState as FormState).validate())
                  validatePassed(context);
              },
              child: Text(
                '提交',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 16,
                ),
              ),
            ),
          ),
          C(30),
        ],
      ),
    );
  }

  Widget formField(String title, int maxSize,
      TextEditingController controller, {String? input}) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Container(
          width: 100,
          height: 40,
          alignment: Alignment.centerRight,
          margin: EdgeInsets.only(
            left: 15,
            right: 10,
          ),
          child: Text(
            title,
            textAlign: TextAlign.center,
            style: TextStyle(
              color: Color(0xff606266),
              fontSize: 14,
            ),
          ),
        ),
        Container(
          width: 220,
          padding: const EdgeInsets.only(
            left: 10,
            right: 15,
          ),
          child: TextFormField(
            controller: controller,
            decoration: InputDecoration(
              hintText: '请填写${input ?? title}',
              hintStyle: const TextStyle(
                fontSize: 14,
                color: Color(0xff606266),
              ),
              border: InputBorder.none,
            ),
            validator: (value) {
              if (value!.trim().isEmpty) {
                return '${input ?? title}不能为空';
              } else if (value.trim().length > maxSize) {
                return '${input ?? title}超出最大长度';
              } else {
                return null;
              }
            },
          ),
          decoration: BoxDecoration(
            border: Border.all(color: Colors.black26, width: 1),
            borderRadius: BorderRadius.circular(5),
          ),
        ),
      ],
    );
  }

  void validatePassed(BuildContext context) {

    html.FormData formData = html.FormData();
    formData.append('pAccount', Application.currentAccount);
    formData.append('pName', _pNameController.text);
    formData.append('pId', _pIdController.text);
    formData.append('cName', _cNameController.text);
    formData.append('year', _yearController.text);
    formData.set('date', _dateMill);
    formData.append('level', _levelController.text);
    formData.appendBlob('file', _file.slice());

    var request = html.HttpRequest();
    request.open('POST', SystemApi.baseUrl + 'apply');
    request.send(formData);

    request.onLoadEnd.listen((event) {
      print('[HttpRequest] response ${request.responseText!}');
      var map = json.decode(request.responseText!);
      if (request.status == 200 && map['code'] == '1') {
        Fluttertoast.showToast(msg: map['msg']);
        Navigator.pop(context);
      } else if (map['code'] != '1') {
        Fluttertoast.showToast(msg: map['msg']);
      } else {
        Fluttertoast.showToast(msg: request.status.toString());
      }
    });
  }
}